
package com.fas.core.plugin.fastdfs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.DownloadCallback;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.csource.fastdfs.UploadCallback;

import com.jfinal.log.Log;

/**
 * FastDFS客户端管理类
 *
 * @Copyright: Copyright (c) 2016 FAS 
 * @anthor yixiaoping<thinker1013@163.com>
 * @since 2016年1月24日 下午10:36:15
 * @version V1.0
 */
public class FastDFSManager {

	private static final Log log = Log.getLog(FastDFSManager.class);

	private static String conf_filename;

	static {
		try {
			conf_filename = FastDFSManager.class.getClassLoader().getResource("fdfs_client.conf")
					.getPath();
			ClientGlobal.init(conf_filename);
			log.info("------------加载fastDFS配置文件成功-------");
		} catch (FileNotFoundException e) {
			log.error("加载fastDFS配置失败，系统退出", e);
		} catch (IOException e) {
			log.error("加载fastDFS配置失败，系统退出", e);
		} catch (Exception e) {
			log.error("异常：",e);
		}
	}


	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/**
	 * 获取文件服务器连接，通过其构建StorageClient
	 * 
	 * @return
	 * @throws IOException
	 */
	public static TrackerServer getTrackerServer() throws IOException {
		TrackerClient tracker = new TrackerClient();
		TrackerServer ts = tracker.getConnection();
		return ts;
	}

	/**
	 * 关闭文件服务器连接
	 * 
	 * @param trackerServer
	 */
	public static void closeTrackerServer(TrackerServer trackerServer) throws IOException {
		if (trackerServer != null) {
			trackerServer.close();
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param fileId
	 * @return
	 * @throws Exception 
	 * @throws MyException
	 */
	public static int deleteFile(String fileId) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		int ret = client.delete_file1(fileId);
		closeTrackerServer(trackerServer);
		return ret;
	}

	/**
	 * 上传文件
	 * 
	 * @param localFile
	 *            本地文件
	 * @param callback
	 *            回调函数
	 * @param metaList
	 *            属性列表，可以为null
	 * @return fileId,文件在服务器的地址
	 * @throws Exception 
	 */
	public static String uploadFile(File localFile, UploadCallback callback,
			NameValuePair[] metaList) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		String fileId = client.upload_file1(null, localFile.length(), callback,
				getExtensionName(localFile.getName()), metaList);
		closeTrackerServer(trackerServer);
		return fileId;
	}

	/**
	 * 上传文件
	 * 
	 * @param localFile
	 *            本地文件
	 * @param metaList
	 *            属性列表，可以为null
	 * @return fileId,文件在服务器的地址
	 * @throws Exception 
	 */
	public static String uploadFile(File localFile, NameValuePair[] metaList) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		String fileId = client.upload_file1(localFile.getAbsolutePath(),getExtensionName(localFile.getName()), metaList);
		closeTrackerServer(trackerServer);
		return fileId;
	}

	/**
	 * 上传文件
	 * 
	 * @param fileBuff
	 *            :字节数组
	 * @param fileExtName
	 *            上传文件的扩展名
	 * @param metaList
	 *            属性列表，可以为null
	 * @return fileId,文件在服务器的地址
	 * @throws Exception 
	 */
	public static String uploadFile(byte[] fileBuff, String fileExtName, NameValuePair[] metaList)
			throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		String fileId = client.upload_file1(fileBuff, fileExtName, metaList);
		closeTrackerServer(trackerServer);
		return fileId;
	}

	/**
	 * 下载文件
	 * 
	 * @param fileId
	 * @return
	 * @throws Exception 
	 */
	public static byte[] downloadFile(String fileId) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		byte[] fileBuff = client.download_file1(fileId);
		closeTrackerServer(trackerServer);
		return fileBuff;
	}

	/**
	 * 下载文件
	 * 
	 * @param fileId
	 * @param fileOffset
	 *            文件起始位置
	 * @param downloadBytes
	 *            下载的字节数
	 * @return
	 * @throws Exception 
	 */
	public static byte[] downloadFile(String fileId, long fileOffset, long downloadBytes)
			throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		byte[] fileBuff = client.download_file1(fileId, fileOffset, downloadBytes);
		closeTrackerServer(trackerServer);
		return fileBuff;
	}

	/**
	 * 下载文件
	 * 
	 * @param fileId
	 * @param localFilename
	 *            下载文件保存到本地的全路径
	 * @return 0:成功，其他失败
	 * @throws Exception 
	 */
	public static int downloadFile(String fileId, String localFilename) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		int ret = client.download_file1(fileId, localFilename);
		closeTrackerServer(trackerServer);
		return ret;
	}

	/**
	 * 下载文件
	 * 
	 * @param fileId
	 * @param callback
	 *            回调函数
	 * @return 0:成功，其他失败
	 * @throws Exception 
	 */
	public static int downloadFile(String fileId, DownloadCallback callback) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		int ret = client.download_file1(fileId, callback);
		closeTrackerServer(trackerServer);
		return ret;
	}

	/**
	 * 下载文件
	 * 
	 * @param fileId
	 * @param fileOffset
	 *            文件的起始位置
	 * @param downloadBytes
	 *            下载的字节数
	 * @param callback
	 *            回调函数
	 * @return 0:成功，其他失败
	 * @throws Exception 
	 */
	public static int downloadFile(String fileId, long fileOffset, long downloadBytes,
			DownloadCallback callback) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		int ret = client.download_file1(fileId, fileOffset, downloadBytes, callback);
		closeTrackerServer(trackerServer);
		return ret;
	}

	/**
	 * 获取文件的属性列表
	 * 
	 * @param fileId
	 * @return
	 * @throws Exception 
	 */
	public static NameValuePair[] getMetadata(String fileId) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		NameValuePair[] nameValuePairs = client.get_metadata1(fileId);
		closeTrackerServer(trackerServer);
		return nameValuePairs;
	}

	/**
	 * 设置文件属性，如果新属性在原属性中存在，则替换值，如果不存在，则增加，新属性中不存在原属性存在，则不变
	 * 
	 * @param fileId
	 * @param metaList
	 * @return 0:成功，其他失败
	 * @throws Exception 
	 */
	public static int setMetadataM(String fileId, NameValuePair[] metaList) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		int ret = client.set_metadata1(fileId, metaList,
				ProtoCommon.STORAGE_SET_METADATA_FLAG_MERGE);
		closeTrackerServer(trackerServer);
		return ret;
	}

	/**
	 * 设置文件属性，替换用新的属性列表替换原有的属性列表
	 * 
	 * @param fileId
	 * @param metaList
	 * @return 0:成功，其他失败
	 * @throws Exception 
	 */
	public static int setMetadataO(String fileId, NameValuePair[] metaList) throws Exception {
		TrackerServer trackerServer = getTrackerServer();
		StorageClient1 client = new StorageClient1(trackerServer, null);
		int ret = client.set_metadata1(fileId, metaList,
				ProtoCommon.STORAGE_SET_METADATA_FLAG_OVERWRITE);
		closeTrackerServer(trackerServer);
		return ret;
	}
}